/* 
 -----------------------------------------------------------------------------
                   Cogaen - Component-based Game Engine (v3)
 -----------------------------------------------------------------------------
 This software is developed by the Cogaen Development Team. Please have a 
 look at our project home page for further details: http://www.cogaen.org
    
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Copyright (c) Roman Divotkey, 2010-2011

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.cogaen.state;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.cogaen.core.Core;
import org.cogaen.core.Service;
import org.cogaen.event.Event;
import org.cogaen.event.EventListener;
import org.cogaen.event.EventManager;
import org.cogaen.event.EventType;
import org.cogaen.logging.LoggingService;

public class GameStateManager implements Service, EventListener {
	
	private static class SetGameStateEvent extends Event {

		private static final EventType TYPE = new EventType("SetGameState");
		private String stateName;

		public SetGameStateEvent(String stateName) {
			this.stateName = stateName;
		}
		
		@Override
		public EventType getType() {
			return TYPE;
		}
		
		public String getStateName() {
			return this.stateName;
		}
	}
	
	// inner class used to store transition data:
	private class Transition {
		private GameState preState;
		private GameState postState;
		private EventType transEventType;
		
		private Transition(GameState fromState, GameState toState, EventType eventType) {
			this.preState = fromState;
			this.postState = toState;
			this.transEventType = eventType;
		}		
	}
	
	public static final String NAME = "cogaen.gamestatemanager";
	public static final String LOGGING_SOURCE = "GameStateManager";
	
	private Core core;
	private LoggingService logger;
	private GameState currentState = null;
	private Map<String, GameState> states = new HashMap<String, GameState>();
	private ArrayList<Transition> transitions = new ArrayList<Transition>();
	
	public static GameStateManager getInstance(Core core) {
		return (GameStateManager) core.getService(NAME);
	}

	@Override
	public String getName() {
		return NAME;
	}
	
	@Override
	public void initialize(Core core) {
		this.core = core;
		this.logger = LoggingService.getInstance(core);
		EventManager.getInstance(core).addListener(this, SetGameStateEvent.TYPE);
	}
	
	public void addState(GameState state) {
		GameState oldState = this.states.put(state.getName(), state);
		if (oldState != null) {
			this.states.put(oldState.getName(), oldState);
			throw new RuntimeException("game state with name '" + state.getName() + "' already exists");
		}
		this.logger.logDebug(LOGGING_SOURCE, "game state '" + state.getName() + "' added");
	}
	
	public GameState getState(String name) {
		GameState state = this.states.get(name);
		if (state == null) {
			throw new RuntimeException("no game state with name '" + name + "' defined");
		}
		return this.states.get(name);
	}
	
	public boolean hasState(String name) {
		return this.states.containsKey(name);
	}
	
	public void setCurrentState(String name) {
		if (!hasState(name)) {
			throw new RuntimeException("no game state with name '" + name + "' defined");			
		}
		EventManager.getInstance(this.core).enqueueEvent(new SetGameStateEvent(name));
	}
	
	public GameState getCurrentState() {
		return this.currentState;
	}
	
	private void switchStateTo(GameState newState) {
		logger.logInfo(LOGGING_SOURCE, "switching to game state '" + newState.getName() + "'");
		if (this.currentState != null) {
			this.currentState.onExit();
		}
		this.currentState = newState;
		this.currentState.onEnter();
	}

	@Override
	public void handleEvent(Event event) {		
		if (event.isOfType(SetGameStateEvent.TYPE)) {
			switchStateTo(getState(((SetGameStateEvent) event).getStateName()));
			return;
		}
		
		for (Iterator<Transition> it = transitions.iterator(); it.hasNext(); ) {
			Transition trans = it.next();
			if(trans.preState == currentState && trans.transEventType.equals(event.getType())) {
				switchStateTo(trans.postState);
				break;
			}
		}
	}	
	
	public void addTransition(String from, String to, EventType eventType) {	
		// retrieve corresponding states
		GameState fromState = getState(from);
		GameState toState = getState(to);
		
		// throw an exception if a transition with equal
		// fromState and equal eventType already exists
		if (hasTransition(fromState, eventType)) {
			throw new RuntimeException("ambiguous transition");
		}
		
		// add new transition
		this.transitions.add( new Transition(fromState, toState, eventType) );
		
		// add manager as listener for corresponding transition event
		EventManager evntMngr = EventManager.getInstance(core);
		if (!evntMngr.hasListener(this, eventType)) {
			evntMngr.addListener(this, eventType);
		}		
	}
	
	private boolean hasTransition(GameState fromState, EventType eventType) {
		for( Iterator<Transition> it = this.transitions.iterator(); it.hasNext(); ) {
			Transition trans = it.next();
			if (trans.preState == fromState && trans.transEventType.equals(eventType)) {
				return true;
			}
		}
		return false;
	}
}
